package com.mixoft.TestApp;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.mixoft.TestApp.R;

public class BaseActivity extends SherlockFragmentActivity implements OnClickListener {

	public static final String TAG = "BaseActivity";
	
	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	
	    // Set up the UI
		setupActionBar();
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
       MenuInflater inflater = getSupportMenuInflater();
       inflater.inflate(R.menu.main, menu);
       
       ImageView mButton = (ImageView) this.findViewById(R.id.btnJobs);
       mButton.setOnClickListener(this);
       
       return super.onCreateOptionsMenu(menu);
    }
	
	/*
	 * Sets up the main action bar
	 */
	private void setupActionBar()
	{
		// Allow custom view in action bar
	    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME |
	    		ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_CUSTOM);
	    getSupportActionBar().setCustomView(R.layout.actionbar_base);
	}

	/*
	 * Inits and commits a transaction to the main fragment
	 */
	private void commitTransaction(FragmentManager fm, Fragment frag, String tag)
	{
		FragmentTransaction ft = fm.beginTransaction();
		ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		ft.addToBackStack(JobsFragment.TAG);
		
		ft.replace(R.id.frgActivityPagerBase, frag, tag);
		
		ft.commit();
	}
	
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId())
		{
			case R.id.btnJobs:
				FragmentManager fm = getSupportFragmentManager();
				Fragment frgInMemory = fm.findFragmentByTag(JobsFragment.TAG);
				String frgCurrent = fm.findFragmentById(R.id.frgActivityPagerBase).getTag();
				
				if (frgCurrent != JobsFragment.TAG && frgInMemory == null) { 
					Log.d(TAG, "User clicked on jobs button, creating new fragment");
					JobsFragment pja = new JobsFragment();
					this.commitTransaction(fm, pja, JobsFragment.TAG);
				} else if (frgInMemory != null && frgCurrent != JobsFragment.TAG) {
					Log.d(TAG, "User clicked on jobs button, restoring fragment from memory");
					this.commitTransaction(fm, frgInMemory, JobsFragment.TAG);
				}
				
				break;
		}
	}
	
}
